package com.hospicpc.demos.controller;


import com.hospicpc.demos.commom.Result;
import com.hospicpc.demos.entity.FollowUser;
import com.hospicpc.demos.entity.LikeArticles;
import com.hospicpc.demos.service.Impl.LikeArticlesServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/likeArticle")
public class LikeArticleController {
    @Autowired
    LikeArticlesServiceImpl likeArticlesService;

    /**
     * 点赞文章
     * @param likeArticles
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody LikeArticles likeArticles) {
        //获取数据
        //点赞的文章id
        Long  toArticleId= likeArticles.getToArticleId();
        //用户id
        Long userId = likeArticles.getUserId();
        //文章类型,0代表ai文章，1代表普通文章
        Integer articleType = likeArticles.getArticleType();

        //判断数据是否存在
        LikeArticles one = likeArticlesService.lambdaQuery().eq(LikeArticles::getUserId, userId)
                .eq(LikeArticles::getToArticleId, toArticleId)
                .eq(LikeArticles::getArticleType, articleType).one();

        boolean res;

        //存在,改变状态
        if(one != null) {
            res = likeArticlesService.lambdaUpdate().eq(LikeArticles::getUserId, userId)
                    .eq(LikeArticles::getToArticleId, toArticleId)
                    .eq(LikeArticles::getArticleType, articleType)
                    .setSql("status = 1")
                    .update();
        } else {
            //不存在,新插入数据
            res = likeArticlesService.save(likeArticles);
        }

        if(res) return Result.success("点赞成功");
        else  return Result.error("服务异常");

    }

    /**
     * 取消点赞文章
     * @param likeArticles
     * @return
     */
    @PostMapping("/del")
    public Result del(@RequestBody LikeArticles likeArticles) {
        //获取数据
        //点赞的文章id
        Long toArticleId = likeArticles.getToArticleId();
        //用户id
        Long userId = likeArticles.getUserId();
        //文章类型,0代表ai文章，1代表普通文章
        Integer articleType = likeArticles.getArticleType();

        boolean res = likeArticlesService.lambdaUpdate().eq(LikeArticles::getUserId, userId)
                .eq(LikeArticles::getToArticleId, toArticleId)
                .eq(LikeArticles::getArticleType, articleType)
                .setSql("status = 0")
                .update();

        if (res) return Result.success("取消点赞成功");
        else return Result.error("服务异常");
    }
}
